package com.goldenlight.fvms.manager.utils;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;

public class CommonUtils {
    private CommonUtils() {
        throw new IllegalStateException("CommonUtils class");
    }

    private static final Logger logger = LoggerFactory.getLogger(CommonUtils.class);

    public static final String STR_WINDOWS = "windows";

    @Value("${longzhu.default-host-ip:}")
    private static String defaultHostIpValue;

    public static long getIdByUUId() {
        String machineId = "1";
        try {
            machineId = getLocalHead();
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        int hashCodeV = UUID.randomUUID().toString().hashCode();
        //有可能是负数
        if (hashCodeV < 0) {
            hashCodeV = -hashCodeV;
        }
        long systemTime = System.currentTimeMillis();
        long uuid = hashCodeV + systemTime;
        String s = machineId + uuid;
        return Long.parseLong(s);
    }


    /**
     * 获取本地IP后两位。
     *
     * @return
     */
    public static String getLocalHead() throws UnknownHostException {
        String localIP = getLocalIP();
        String[] split = localIP.split("\\.");
        return split[3];
    }

    /**
     * 获取本地IP。
     *
     * @return
     * @throws UnknownHostException
     * @throws SocketException
     */
    public static String getLocalIP() throws UnknownHostException {
        if (isWindowsOS()) {
            return InetAddress.getLocalHost().getHostAddress();
        } else {
            return getLinuxLocalIp();
        }
    }

    /**
     * 判断是否是Windows。
     *
     * @return
     */
    private static boolean isWindowsOS() {
        boolean isWindowsOS = false;
        String osName = System.getProperty("os.name");
        if (osName.toLowerCase().indexOf(STR_WINDOWS) > -1) {
            isWindowsOS = true;
        }
        return isWindowsOS;
    }

    /**
     * Linux下获取本地IP。
     *
     * @return
     */
    private static String getLinuxLocalIp() {
        String ip = "";
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface networkInterface = en.nextElement();
                String name = networkInterface.getName();
                if (!name.contains("docker") && !name.contains("lo")) {
                    ip = marryIp(networkInterface, ip);
                }
            }
        } catch (SocketException ex) {
            ip = defaultHostIpValue;
            logger.error(ex.getMessage());
        }
        return ip;
    }

    private static String marryIp(NetworkInterface networkInterface, String ip) {
        for (Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
            InetAddress inetAddress = enumIpAddr.nextElement();
            if (!inetAddress.isLoopbackAddress()) {
                String ipaddress = inetAddress.getHostAddress();
                if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {
                    ip = ipaddress;
                }
            }
        }
        return ip;
    }


    public static <T> Boolean isNotEmpty(Collection<T> collection) {
        return null != collection && !collection.isEmpty();
    }

    public static <T> T convert(Object object, Class<T> c) {
        return JSONObject.parseObject(JSONObject.toJSONString(object), c);
    }

    public static <T> List<T> convertList(Object object, Class<T> c) {
        return JSON.parseArray(JSONObject.toJSONString(object), c);
    }

}
